from flask import Blueprint, request, redirect, url_for, render_template

from day15.student_manager import StudentManager

stu_manager_bp=Blueprint("stu_bp",__name__,url_prefix="/stu")

student_manager=StudentManager()


@stu_manager_bp.route("/list")
def list():
    search_name = request.args.get("search")
    if search_name:
        return render_template("list.html", students=student_manager.find_user(search_name))
    return render_template("list.html", students=student_manager.students)

@stu_manager_bp.route("/add",methods=["get","post"])
def add():
    error = None
    if request.method == "POST":
        sid = request.form.get("sid")
        name = request.form.get("name")
        gender = request.form.get("gender")
        age = request.form.get("age")
        s_class = request.form.get("s_class")
        email = request.form.get("email")
        dress = request.form.get("dress")

        error=student_manager.valid_check(name,gender,age,s_class,email,dress)
        if not error:
            student_manager.add_student(name,gender,age,s_class,email,dress)
            return redirect(url_for("stu_bp.list"))
    return render_template("add.html", error=error)

@stu_manager_bp.route("/modify/<int:sid>",methods=["get","post"])
def modify(sid):
    student=student_manager.get_student(sid)
    if not student:
        return f"学员信息找不到",404
    error = None
    if request.method == "POST":
        name = request.form.get("name")
        gender = request.form.get("gender")
        age = request.form.get("age")
        s_class = request.form.get("s_class")
        email = request.form.get("email")
        dress = request.form.get("dress")
        error = student_manager.valid_check(name, gender, age, s_class, email, dress)
        if not error:
            student_manager.update_student(sid,name, gender, age, s_class, email, dress)
            return redirect(url_for("stu_bp.list"))
    return render_template("modify.html",student=student,error=error)


@stu_manager_bp.route("/delete/<int:sid>")
def delete(sid):
    student_manager.delete_student(sid)
    return render_template("list.html",students=student_manager.students)
